package com.mediacloud.app.newsmodule.fragment.imagetext

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.text.Html
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextUtils
import android.text.style.StyleSpan
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewStub
import android.view.ViewTreeObserver
import android.webkit.JsPromptResult
import android.webkit.JsResult
import android.webkit.URLUtil
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import com.eventTrack.TXReportManager
import com.mediacloud.app.appfactory.cache.AppConfig
import com.mediacloud.app.assembly.util.AssetsManager
import com.mediacloud.app.assembly.util.FileUtil
import com.mediacloud.app.assembly.util.StringUtils
import com.mediacloud.app.assembly.util.Utility
import com.mediacloud.app.assembly.util.isFastClick
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.kt.TypeX
import com.mediacloud.app.model.utils.NeedTokenType
import com.mediacloud.app.model.utils.SDKNewsItemJump
import com.mediacloud.app.model.utils.ViewUtils
import com.mediacloud.app.model.utils.WebViewUtils
import com.mediacloud.app.model.view.WebBrowser
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.activity.HandleDataCollectActivity
import com.mediacloud.app.newsmodule.activity.ImageTextDetailActivity2
import com.mediacloud.app.newsmodule.activity.WebViewPageActivity
import com.mediacloud.app.newsmodule.fragment.baoliao.TransUtils
import com.mediacloud.app.newsmodule.model.JSImgItem
import com.mediacloud.app.newsmodule.newsdetail_component.NewsDetailComponentUtils
import com.mediacloud.app.newsmodule.pay.GivenMoneyPeopleListAdapter
import com.mediacloud.app.newsmodule.pay.GivenMoneyResult
import com.mediacloud.app.newsmodule.pay.NormalPayUtil
import com.mediacloud.app.newsmodule.pay.NormalPayUtil.Others
import com.mediacloud.app.newsmodule.pay.PaidContentListener
import com.mediacloud.app.newsmodule.pay.PaidMetas
import com.mediacloud.app.newsmodule.utils.FacadeInvoker
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils
import com.mediacloud.app.newsmodule.utils.WebViewLinkCMSNewsHandle
import com.mediacloud.app.newsmodule.view.BaseSpiderView
import com.mediacloud.app.newsmodule.view.WeatherSetter
import com.mediacloud.app.newsmodule.view.WrapLinearLayout
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.enums.XKey
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.mediacloud.app.user.model.UserInfo
import com.mediacloud.app.user.utils.RxUtils
import com.tencent.mmkv.MMKV
import io.reactivex.functions.Consumer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import org.jsoup.select.Elements


//fun ImageTextDetailFragment.parseHtml(html: String): Job {
//    val scope = CoroutineScope(Dispatchers.Default)
//    val content =
//        "<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"https://web.dev.chinamcloud.cn/cms/rmt1589/css/cssbase.css\"><script type=\"text/javascript\">#appfactoryContentJSHead#</script><meta name=\"format-detection\" content=\"telephone=no\"><meta name=\"viewport\" content=\"width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no\"><style>@font-face{font-family: appfactoryClientFont;src: url(\"APPFACTORY_CLIENT_LOCAL_FONT_SRC\");}body * {font-family: appfactoryClientFont;word-wrap: break-word;}</style><script src=\"file:///android_asset/web/webnews.txt\"></script><script src=\"file:///android_asset/web/webiframe.txt\"></script></head><body><div style=\"font-family:PingFang SC;font-size:小四px;letter-spacing:1px;line-height: 1.75em;margin-top: 26px;margin-bottom: 26px\" id=\"editWrap\"><p> 大部分战队开始休假</p><p> 随着各战队的春季赛的告一段落，选手们也是已经进入到休赛期了，距离夏季赛还有比较长的时间，这段时间对于选手们来说，是可以很好的恢复状态和放松自己的一个假期，也有部分选手已经回家了，当然大部分选手都是选择留在基地休息，也有选手是计划着要去出游的，毕竟假期的时间那么长，选手们也是可以做一些自己想做的事情，比如小情侣之间约约会，一起出去玩一下，或者是跟队友们外出游玩，都是很不错的选择。</p><p class=\"\" data-type=\"image\" style=\"text-align:center;\"><img src=\"https://image.csp.chinamcloud.com/cms/rmt8377/upload/HttpImage/mrtpsc/2021/04/16/e1d24d60c41d452ab3dd49a6e42ee62d.jpg\" style=\"max-width:640px;\" title=\"\" alt=\"\" data-type=\"image\" android_imgindex=\"0\" onclick=\"webImgClick(this);\" onload=\"resizeNativeControl(this)\" onerror=\"resizeNativeControl(this)\"></p><p> 选手陆续开播</p><p> 当然直播对于假期中的选手来说是首选，近日选手们也是陆续开了直播，像卡萨，rookie也是在直播间整活，卡萨化身“灵魂画手”，画了不少LPL选手，rookie这边则是照常跟粉丝们聊天，在直播中打排位，不过近两次rookie打排位都不是很顺利，上一次是一直进不去游戏，还有遇到闪退的问题，也是将rookie给气到了，这一次rookie是打的国服，没有了闪退的问题。</p><p class=\"\" data-type=\"image\" style=\"text-align:center;\"><img src=\"https://image.csp.chinamcloud.com/cms/rmt8377/upload/HttpImage/mrtpsc/2021/04/16/253617424ce84850ac7cf237b7b87166.jpg\" style=\"max-width:640px;\" title=\"\" alt=\"\" data-type=\"image\" android_imgindex=\"1\" onclick=\"webImgClick(this);\" onload=\"resizeNativeControl(this)\" onerror=\"resizeNativeControl(this)\"></p><p> 不过rookie使用滑板鞋，引起了观众们的热议，粉丝们不想要看到rookie玩这个英雄，不希望看到滑板鞋在IG的地位越来越高，但是奈何rookie对这个英雄以及喜欢上了，rookie还跟大家透露这个英雄有多好玩，并且告知粉丝，这个英雄是Theshy推荐他去玩的，说是玩好了可以中上摇摆，听到rookie这一番话，粉丝们更是担心了，毕竟没有战队会用滑板鞋做中上摇摆，这种比较“阴间”的摇摆，很容易将自己给赔进去，最后得不偿失。</p><p class=\"\" data-type=\"image\" style=\"text-align:center;\"><img src=\"https://image.csp.chinamcloud.com/cms/rmt8377/upload/HttpImage/mrtpsc/2021/04/16/6ca31b3395314f17a41fa7b783fdd646.jpg\" style=\"max-width:640px;\" title=\"\" alt=\"\" data-type=\"image\" android_imgindex=\"2\" onclick=\"webImgClick(this);\" onload=\"resizeNativeControl(this)\" onerror=\"resizeNativeControl(this)\"></p><p> 粉丝们对滑板鞋有这么大的“恶意”也是可以理解的，这一个春季赛IG多次拿出滑板鞋和辛德拉的阵容，结果导致比赛溃败，粉丝们也是对滑板鞋产生了畏惧，不过rookie玩的很开心，哪怕在游戏当中接连阵亡，打出了超鬼又超鬼的数据，Rookie还是乐在其中，看到这样的rookie，粉丝们也是绝望了，看来想要剔除滑板鞋这个英雄是不现实的事情。</p><p class=\"\" data-type=\"image\" style=\"text-align:center;\"><img src=\"https://image.csp.chinamcloud.com/cms/rmt8377/upload/HttpImage/mrtpsc/2021/04/16/67ba3dd4d1144bbba32bdae2d2d56c1e.jpg\" style=\"max-width:640px;\" title=\"\" alt=\"\" data-type=\"image\" android_imgindex=\"3\" onclick=\"webImgClick(this);\" onload=\"resizeNativeControl(this)\" onerror=\"resizeNativeControl(this)\"></p><p> rookie直播间有节奏</p><p> 除了有粉丝们在吐槽滑板鞋这个英雄之后，在直播间还有一些故意带节奏的水友，毕竟这个赛季IG的成绩这么的糟糕，也是让更多的“黑子”有了可以黑的东西，IG选手开播的不多，难得rookie开了直播，这些不安好心的“黑子”也是赶来围观了，也在弹幕中刻意“恶心”在，在直播间可以看到有很多“黑称”，因为IG战绩不佳，rookie在赛场上的表现也不是很理想，所以舆论环境也发生了变化，就连rookie的舆论都开始有负面的节奏。</p><p class=\"\" data-type=\"image\" style=\"text-align:center;\"><img src=\"https://image.csp.chinamcloud.com/cms/rmt8377/upload/HttpImage/mrtpsc/2021/04/16/d195c2ee5cf4465595dc06e4a7a86eac.jpg\" style=\"max-width:640px;\" title=\"\" alt=\"\" data-type=\"image\" android_imgindex=\"4\" onclick=\"webImgClick(this);\" onload=\"resizeNativeControl(this)\" onerror=\"resizeNativeControl(this)\"></p><p> 在这场直播当中，有水友在弹幕询问rookie，IG的“复活赛”什么时候打，相信观众们也知道这个赛季的季后赛四强是采用的双败赛制，这样的赛制也是让战队可以有多一次机会在赛场上战斗，比如EDG和RNG战队在首轮战败之后，在败者组还有一次战斗的机会，这样的赛制也是让队伍有了更大的希望，当然这仅仅是对强队来说是好事，对于“伪强队”来说并不是一件好事，而IG被询问“复活赛”的事情，也是非常嘲讽的。</p><p class=\"\" data-type=\"image\" style=\"text-align:center;\"><img src=\"https://image.csp.chinamcloud.com/cms/rmt8377/upload/HttpImage/mrtpsc/2021/04/16/a91feb8b63f5426691ad15851a3cb892.jpg\" style=\"max-width:640px;\" title=\"\" alt=\"\" data-type=\"image\" android_imgindex=\"5\" onclick=\"webImgClick(this);\" onload=\"resizeNativeControl(this)\" onerror=\"resizeNativeControl(this)\"></p><p> rookie回击弹幕</p><p> 这个赛季的IG依旧是季后赛一轮游，最终是拿到了第九名的名次，复活赛跟IG是没有关系的，所以弹幕这一波嘲讽也是司马昭之心，rookie在看到了这些弹幕之后，也是很高情商的回应了，rookie笑着回应弹幕，回击那些询问IG复活赛的水友，直言如果你们可以给IG弄来一个复活赛的话，IG当场就能够复活，马上复活给大家看，看来rookie对于水友们恶搞的这些舆论已经是看得明白了，也知道这些人是故意在带IG的节奏。</p><p class=\"\" data-type=\"image\" style=\"text-align:center;\"><img src=\"https://image.csp.chinamcloud.com/cms/rmt8377/upload/HttpImage/mrtpsc/2021/04/16/6260eb702e7c40eb990e0ade2e69460f.jpg\" style=\"max-width:640px;\" title=\"\" alt=\"\" data-type=\"image\" android_imgindex=\"6\" onclick=\"webImgClick(this);\" onload=\"resizeNativeControl(this)\" onerror=\"resizeNativeControl(this)\"></p><p> 只是IG确实是战绩非常糟糕，所以用玩笑话化解是最好的办法，后面还有弹幕故意询问rookie会不会使用妖姬，rookie也是学着水友故意的语气回答，rookie表示自己不会玩妖姬，但是有妖姬的皮肤，不得不说rookie这一波回应伤害直接拉满，这一个回答堪称满分，也打脸这些故意带节奏的人，不过对于rookie在直播中频繁使用滑板鞋，粉丝们是真的要产生PTSD了，生怕夏季赛的IG会将滑板鞋全面使用起来。</p><p class=\"\" data-type=\"image\" style=\"text-align:center;\"><img src=\"https://image.csp.chinamcloud.com/cms/rmt8377/upload/HttpImage/mrtpsc/2021/04/16/da1570a82448407fbec6c5b781bdf4f5.jpg\" style=\"max-width:640px;\" title=\"\" alt=\"\" data-type=\"image\" android_imgindex=\"7\" onclick=\"webImgClick(this);\" onload=\"resizeNativeControl(this)\" onerror=\"resizeNativeControl(this)\"></p><p> 从直播的操作看，rookie对滑板鞋的操作算不上非常精练，也没有Theshy那种感觉，拿出来摇到中路的话，并不是一个理智的选择，毕竟滑板鞋这个英雄的可塑性比较低，很容易阵亡，如果是放在C位使用的话，一个超鬼的滑板鞋，对对面来说是完全可以不放在眼中的，所以说IG这一手中上摇摆滑板鞋，并不被看好。</p><p class=\"\" data-type=\"image\" style=\"text-align:center;\"><img src=\"https://image.csp.chinamcloud.com/cms/rmt8377/upload/HttpImage/mrtpsc/2021/04/16/75283c387f64430682dce3c4836658f7.jpg\" style=\"max-width:640px;\" title=\"\" alt=\"\" data-type=\"image\" android_imgindex=\"8\" onclick=\"webImgClick(this);\" onload=\"resizeNativeControl(this)\" onerror=\"resizeNativeControl(this)\"></p><p> 不过看到rookie在直播间可以跟水友们对话自如，“装杯”的话是信手拈来，粉丝们也是很好奇rookie从哪里学来的这么多的骚话，可以将水友们怼的没话说，还知道踩着“黑子”来抬自己一手，确实是有进步了，如果是Theshy的直播间遭遇到这样带有嘲讽恶意的弹幕，想来也只是一刷就过去了，也不会引起Theshy的注意和回应。</p><p class=\"\" data-type=\"image\" style=\"text-align:center;\"><img src=\"https://image.csp.chinamcloud.com/cms/rmt8377/upload/HttpImage/mrtpsc/2021/04/16/e1917cc3ecbd4383a8600876f861fe75.jpg\" style=\"max-width:640px;\" title=\"\" alt=\"\" data-type=\"image\" android_imgindex=\"9\" onclick=\"webImgClick(this);\" onload=\"resizeNativeControl(this)\" onerror=\"resizeNativeControl(this)\"></p><p> 毕竟Theshy的中文仅限于说，读这一块对于Theshy来说还是比较困难的，也是因为这样的原因，黑子一般都不乐意在THeshy直播间刷，因为存在感太低了，对选手造成的影响不大，这倒是给Theshy省心了，不过rookie对于读取中文还是有一定的级数的，所以会看懂一些不太好的弹幕，幸好rookie的心态好，脾气也好，所以也没有引起什么大节奏。你怎么看rookie加大使用滑板鞋？</p><p><br></p></div>#appfactoryContentJS#\n" +
//                " </body></html>"
//    return scope.launch {
//        withContext(Dispatchers.Main) {
//            mWebView.loadDataWithBaseURL(null, content, "text/html; charset=utf-8", "utf-8", null)
//        }
//    }
//}

@SuppressLint("ClickableViewAccessibility")
fun ImageTextDetailFragment2.parseHtml(html: String): Job {

    val scope = CoroutineScope(Dispatchers.Default)


    return scope.launch {
        ImageTextDetailFragment2.iframe_vote_releationship.clear()
        val doc = Jsoup.parse(html)
        val bodyNode: Elements? = doc.getElementsByTag("head")
        if (bodyNode != null && bodyNode.size > 0) {
            bodyNode[0].append("\n<script src=\"file:///android_asset/web/webnews.txt\"/>")
            bodyNode[0].append("\n<script src=\"file:///android_asset/web/webiframe.txt\"/>")
        }
        val imgTags = doc.getElementsByTag("img")
        for (i in 0 until imgTags.size) {
            val imgElement = imgTags[i]
            val imgUrl = imgElement.attr("src")
            if (imgTags.isNullOrEmpty() || imgUrl.contains("tag=1")) { //取消内链新闻的图片点击
                break
            }
            //<img>标签是否在<a>标签里
            val isInATag = (imgElement.parentNode() as Element).tagName() == "a"
            val imgItem = JSImgItem()
            imgItem.info = article.getTitle()
            imgItem.src = imgUrl
            imgItem.hasATag = isInATag
            imgElement.attr("android_imgindex", webImages.size.toString())
            webImages.add(imgItem)
            imgElement.attr("onclick", ImageTextDetailFragment2.WebImgClick + "(this);")
//                imgElement.attr("onload", "resizeNativeControl(this)")
//                imgElement.attr("onerror", "resizeNativeControl(this)")
        }
        //把h5的音视频给移除了
        val videoNodes = doc.getElementsByTag("video")
        if (videoNodes != null && videoNodes.size > 0) videoNodes.remove()
        val audioNodes = doc.getElementsByTag("audio")
        if (audioNodes != null && audioNodes.size > 0) audioNodes.remove()
        if (webViewInsertHandle != null) {
            webViewInsertHandle.parseHTMLVideoNode(doc)
            webViewInsertHandle.parseHTMLAudioNode(doc)
        }

        //投票的iframe处理验签
        val iframeNodes = doc.getElementsByTag("iframe")

        val key = "act_id"
        var host = null
        iframeNodes.forEach { iframe ->
            if (iframe.hasAttr("morefun") && iframe.hasAttr("src")) {
                iframe.attr("scrolling", "no")
                iframe.attr("frameborder", "no")
                iframe.attr("border", "0")
                iframe.attr("onload", "resizeNativeControl(this)")
                iframe.attr("onresize", "resizeNativeControl(this)")
                val src = iframe.attr("src")
                val iframeId = iframe.attr("id")
                if (URLUtil.isNetworkUrl(src)) {
                    val params: MutableMap<String, String> = WebViewUtils.getUrlParms(src)
                    if (params.containsKey(key) && !TextUtils.isEmpty(params[key])) {
                        ImageTextDetailFragment2.iframe_vote_releationship[params[key]] =
                            iframeId
                    }
                    /*  try {
                          URL url = new URL(src);
                          if (TextUtils.isEmpty(host))
                              host = url.getHost();
                      } catch (Exception e) {
                          e.printStackTrace();
                      }*/
                }
                iframe.attr("src", src)
            }
        }

        val scriptTag: Elements? = doc.getElementsByTag("script")
        scriptTag?.let {
            if (it.size > 0 && !TextUtils.isEmpty(host)) {//TODO Fix 这里拷贝的以前的逻辑。很明显host一致为null 不会进到里面的。 这里需要排查
                //domain动态替换的
                val domain = "document.domain = '$host';\r\n"
                it[0].append(domain);
            }
        }
        var result = doc.toString()
        if ("1" == activity?.resources?.getString(R.string.use_custom_font)) {
            val fontResId = Utility.getResId(activity, "font", Utility.RAW)
            if (fontResId > 0) {
                try {
                    val fontDes =
                        FileUtil.CACHE + requireContext().packageManager.getPackageInfo(
                            requireContext().packageName,
                            0
                        ).versionName + "font.ttf"
                    if (!FileUtil.isFileEnable(fontDes)) {
                        val success =
                            AssetsManager.copyRawFile2SDCard(activity, fontResId, fontDes)
                        result = result.replace(
                            ImageTextDetailFragment2.APPFACTORY_CLIENT_LOCAL_FONT_SRC.toRegex(),
                            ImageTextDetailFragment2.NATIVE_STORAGE_PREFIX + fontDes
                        )
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }

        withContext(Dispatchers.Main) {
            if (activity == null) return@withContext
            mWebView.setWebChromeClient(object : WebBrowser.WebChrome(activity, mWebView) {
                override fun onJsConfirm(
                    view: WebView?,
                    url: String?,
                    message: String?,
                    result: JsResult?
                ): Boolean {
                    val value = super.onJsConfirm(view, url, message, result)
                    try {
                        webViewInsertHandle?.resizeNativeControl()
                    } catch (e: java.lang.Exception) {
                        e.printStackTrace()
                    }
                    return value
                }


                override fun onJsAlert(
                    view: WebView?,
                    url: String?,
                    message: String?,
                    result: JsResult?
                ): Boolean {
                    val value = super.onJsAlert(view, url, message, result)
                    try {
                        webViewInsertHandle?.resizeNativeControl()
                    } catch (e: java.lang.Exception) {
                        e.printStackTrace()
                    }
                    return value
                }


                override fun onJsPrompt(
                    view: WebView?,
                    url: String?,
                    message: String?,
                    defaultValue: String?,
                    result: JsPromptResult?
                ): Boolean {
                    val value = super.onJsPrompt(view, url, message, defaultValue, result)
                    try {
                        webViewInsertHandle?.resizeNativeControl()
                    } catch (e: java.lang.Exception) {
                        e.printStackTrace()
                    }
                    return value
                }
            })
            mWebView.setWebViewClient(object : WebBrowser.WebClient(activity, mWebView) {
                override fun onPageFinished(view: WebView?, url: String?) {
                    super.onPageFinished(view, url)
                    isLoaded = true
                    if (!isOtherAdded && !isDispose) {
                        isOtherAdded = true
                        if (!isCalendar) {
                            initReadNews()
                            setDisclaimer()
                            zerenbianji()
                            initReward()
                            setKeyWord()
                            setOriginAndReprint()//这里是为了防止接口回来页面还没加载出来的情况
                        }
                        if (mArticleItemReciver != null) { //这里说明取到了详情数据 直接执行下面的流程
                            onDetailNext = false
                            var isEpaper = false
                            if (activity is ImageTextDetailActivity2) {
                                isEpaper = (activity as ImageTextDetailActivity2).isEpaper
                            }
                            if (!isEpaper && !isCalendar) {
                                addComponent()
                            }
                        } else {
                            onDetailNext = true
                        }
                    }
                }

                override fun shouldInterceptRequest(
                    view: WebView?,
                    u: String?
                ): WebResourceResponse? {

                    var url = u
                    if (activity != null) {
                        val params: Map<String, String> = WebViewUtils.getUrlParms(url)
                        if (WebViewUtils.judgeDelayLoginParam(
                                activity,
                                NeedTokenType.Delayed,
                                params
                            )
                        ) {
                            if (WebViewUtils.judgeDelayLoginParamAndRefresh(
                                    activity,
                                    NeedTokenType.Delayed,
                                    params
                                )
                            ) {
                                //这个图文的不晓得要改不，先改到起，后续发现不对就注释掉
                                url = mWebView.url
                            }
                            if (!UserInfo.isLogin(activity)) {
                                intoLogin(activity)
                            }
                        }
                    }
                    return super.shouldInterceptRequest(view, url)
                }

                override fun shouldOverrideUrlLoading(view: WebView?, u: String?): Boolean {
                    Log.w("XXX", "shouldOverrideUrlLoading$u")
                    var url = u
                    url = WebViewUtils.replaceDoubleQuesMark(url)
                    val params: MutableMap<String, String> = WebViewUtils.getUrlParms(url)
                    if (WebViewUtils.judgeDelayLoginParam(
                            activity,
                            NeedTokenType.Delayed,
                            params
                        )
                    ) {
                        if (WebViewUtils.judgeDelayLoginParamAndRefresh(
                                activity,
                                NeedTokenType.Delayed,
                                params
                            )
                        ) {
                            //这个图文的不晓得要改不，先改到起，后续发现不对就注释掉
                            url = mWebView.url
                        }
                        if (!UserInfo.isLogin(activity)) {
                            intoLogin(activity)
                        }
                    } else if (!WebViewLinkCMSNewsHandle.handleCMSNews(
                            url,
                            activity,
                            article,
                            catalogItem
                        ) && !SDKNewsItemJump.isMoreFunSDK(activity, url)
                    ) {
                        //  return super.shouldOverrideUrlLoading(view, url);
                        val articleItem = ArticleItem()
                        articleItem.isComment = "0"
                        articleItem.content = "APPTAG"
                        articleItem.isLinkNews = false
                        var type = ""
                        if (url!!.contains("type=")) {
                            type = url!!.split("type=")[1]
                            if (type.contains("&")) {
                                type = type.split("&")[0]
                            }
                        }
                        var articleid = "0"
                        if (url!!.contains("articleid=")) {
                            articleid = url!!.split("articleid=")[1]
                            if (articleid.contains("&")) {
                                articleid = articleid.split("&")[0]
                            }
                        }
                        if(!TextUtils.isEmpty(articleid)){
                            articleItem.id = articleid.toLong()
                        }

                        if(TextUtils.isEmpty(type)){
                            articleItem.setType(TypeX.NEWS.LINK)
                        }else{
                            articleItem.setType(type.toInt())
                        }
                        articleItem.url = url
                        //暂时不要标题
                        articleItem.title = "  "
                        val needToken = WebViewUtils.getNeedTokenTag(url)
                        val canCollect = false
                        val canShare = true
                        if (catalogItem == null) catalogItem = CatalogItem()
                        val intent = Intent()
                        intent.putExtra(Intent.EXTRA_REFERRER, 1)
                        NewsItemClickUtils.OpenItemNewsHandle(
                            activity,
                            articleItem.getType(),
                            articleItem,
                            catalogItem,
                            intent,
                            needToken,
                            canCollect,
                            canShare
                        )
                    }

                    return true
                }
            })
            result = result.replace(">\\s+<".toRegex(), "><")

            if (result.contains("overflow-y")){
                //放大字体后滑动会有问题，针对这种情况单独处理一下
                if (MMKV.defaultMMKV().getInt(XKey.NEWS_FONT_SIZE, 1) != 1)
                    resizeFont(1, AppConfig.zoomSize[1]!!)
                mWebView.setOnTouchListener { _: View, event: MotionEvent ->
                    mWebView.requestDisallowInterceptTouchEvent(
                        event.action != MotionEvent.ACTION_UP
                    )
                    false
                }
            }
            mWebView.loadDataWithBaseURL(
                null,
                HtmlFormat.getNewContent(result),
                "text/html; charset=utf-8",
                "utf-8",
                null
            )
            mWebView.viewTreeObserver.addOnPreDrawListener(object :
                ViewTreeObserver.OnPreDrawListener {
                var oldHeight = mWebView.measuredHeight
                override fun onPreDraw(): Boolean {
                    if (mWebView.measuredHeight > oldHeight) {
                        closeActivityStateView()
                        webViewInsertHandle.resizeNativeControl()
                        mWebView.viewTreeObserver.removeOnPreDrawListener(this)
                        val childHeight = mScrollView.getChildAt(0).measuredHeight
                        val percent =
                            (mScrollView.scrollY + mScrollView.measuredHeight) * 1f / childHeight
                        if (activity is HandleDataCollectActivity) {
                            (activity as HandleDataCollectActivity?)!!.setScrollProp(percent)
                        }
                    } else {
                        oldHeight = mWebView.measuredHeight
                    }
                    return true
                }
            })

        }
    }

}

object HtmlFormat {

    fun getNewContent(htmltext: String): String {

        val doc = Jsoup.parse(htmltext)
        val elements = doc.getElementsByTag("img")
        for (element in elements) {
            element.attr("max-width", "100%").attr("height", "auto")
        }

        return doc.toString().replace("margin-top: 15px", "margin-top: 5px")
    }
}

fun ImageTextDetailFragment2.addComponent() {

    mRootView.findViewById<ViewStub>(R.id.vsRelate).inflate()
    container = mRootView.findViewById(R.id.relateLayout)
    //添加分享组件
    NewsDetailComponentUtils.addShareComponent(
        mRootView.findViewById(R.id.relateLayout),
        activity,
        this
    )

    article.extension?.relaSpecial?.let {
        if (it.isNotEmpty() && it!="{}"){
            NewsDetailComponentUtils.addTopicComponent(
                mRootView.findViewById(R.id.relateLayout),
                activity,it,
                this
            )
        }

    }


    if (!fromShanShiPin && !isFromeVod && mArticleItemReciver.components != null && mArticleItemReciver.components.size > 0) {
        article.mShowSwitch = mShowSwitch
//        mRootView.findViewById<ViewStub>(R.id.vsRelate).inflate()
//
//        container = mRootView.findViewById(R.id.relateLayout)

        NewsDetailComponentUtils.addComponentList(
            mRootView.findViewById(R.id.relateLayout),
            mArticleItemReciver.components,
            article,
            activity,
            childFragmentManager,
            1,
            this
        )
        try {
            container?.removeCallbacks(exposureTask)
            container?.postDelayed(exposureTask,TXReportManager.EXPOSURE_DELAY)
        }catch (e:Exception){

        }
        /*container?.let{
           it.postDelayed(exposureTask,TXReportManager.EXPOSURE_DELAY)
        }*/
//     var scrollView:SmartScrollView?= if(mScrollView is SmartScrollView){mScrollView as SmartScrollView
//     }else {null}
//        DCPTManager.addComponent(mRootView.findViewById(R.id.relateLayout),null,mArticleItemReciver.components,article, childFragmentManager, 1, this)
    }
}

/**
 * 打赏 在网页加载完成后再去设置
 */
fun ImageTextDetailFragment2.initReward() {
    if ("2" == article.payType) {
        (mRootView.findViewById<View>(R.id.vsReward) as ViewStub).inflate()
        rewardView = mRootView.findViewById(R.id.giveMoney)
        giveMoneyPeople = mRootView.findViewById(R.id.giveMoneyPeople)
        tvRewardTitle = mRootView.findViewById(R.id.giveMoneyTitle)
        rewardView.setOnClickListener(this)
        givenMoneyPeopleListAdapter = GivenMoneyPeopleListAdapter(activity!!)
        giveMoneyPeople.layoutManager =
            ViewUtils.generateRecyclerGridLayoutManager(activity, true, 5)
        giveMoneyPeople.adapter = givenMoneyPeopleListAdapter
        refreshGivenMoneyHead()
    }
}

fun ImageTextDetailFragment2.refreshGivenMoneyHead() {
    val a = DataInvokeUtil.getZiMeiTiApi().getGivenMoneyPeople(0, article.cps_id).compose(
        TransUtils.fastJSonTransform(
            GivenMoneyResult::class.java
        )
    ).compose(RxUtils.schedulersTransformer())
        .subscribe(Consumer { data ->
            if (activity == null || requireActivity().isFinishing) {
                return@Consumer
            }
            if (isDetached || isDispose() || isRemoving) return@Consumer
            Log.w(ImageTextDetailFragment2.TAG, "" + data)
            if (data.state) {
                data?.data?.meta?.let {
                    if (it.isNotEmpty()) {
                        giveMoneyPeople.visibility = View.VISIBLE
                        tvRewardTitle.visibility = View.VISIBLE
                        //设置打赏人数
                        val formatStr =
                            "<font color=\"#999999\">-</font> 当前已有 <font color=\"#FF0000\">%s</font> 人打赏文章<font color=\"#999999\"> -</font>"
                        tvRewardTitle.text = Html.fromHtml(String.format(formatStr, it.size))
                        givenMoneyPeopleListAdapter.data.clear()
                        givenMoneyPeopleListAdapter.data.addAll(it)
                        givenMoneyPeopleListAdapter.notifyDataSetChanged()
                    }
                }
            }
        }, Consumer { throwable ->
            if (activity == null || requireActivity().isFinishing) {
                return@Consumer
            }
            if (isDetached || isDispose() || isRemoving) return@Consumer
            Log.w(ImageTextDetailFragment2.TAG, "" + throwable.message)
        })
}

/**
 * 关键字 在网页加载完成后再去设置
 */
fun ImageTextDetailFragment2.setKeyWord() {

    if (serverInfo.content_show_keyword == 1 && article.keyword != null && article.keyword.size > 0) {
        mRootView.findViewById<ViewStub>(R.id.vsKeyWord).inflate()
        val layoutKeyWord = mRootView.findViewById<WrapLinearLayout>(R.id.keyContainer)
        for (key in article.keyword) {
            if (!TextUtils.isEmpty(key)) {
                val view = LayoutInflater.from(activity).inflate(R.layout.keyword_item, null)
                val ktv = view.findViewById<TextView>(R.id.ktv)
                ktv.text = key
                layoutKeyWord.addView(ktv)
            }
        }
        if (layoutKeyWord.childCount > 0) {
            layoutKeyWord.visibility = View.VISIBLE
        } else {
            layoutKeyWord.visibility = View.GONE
        }
    }
}

/**
 * 设置新闻标签和来源时间等的布局样式
 */
fun ImageTextDetailFragment2.setNewsTitle() {
//    tvNewsTitle.text = article.getTitle()
    tvNewsTitle.text =
        if (article.real_title.isNullOrEmpty()) article.getTitle() else article.real_title
    if ("2" == AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.title_align) {
        tvNewsTitle.gravity = Gravity.CENTER
    } else {
        tvNewsTitle.gravity = Gravity.START
    }

    //
    if (!TextUtils.isEmpty(article.shortTitle) && detailActivity()?.isEpaper!!) {
        text_short_title.visibility = View.VISIBLE
        text_short_title.text = article.shortTitle
    } else {
        text_short_title.visibility = View.GONE
    }

    if (!TextUtils.isEmpty(article.subTitle) && detailActivity()?.isEpaper!!) {
        text_sub_tile.visibility = View.VISIBLE
        text_sub_tile.text = article.subTitle
    } else {
        text_sub_tile.visibility = View.GONE
    //    normalInfoLayout?.setPadding(0, DisplayUtil.dip2px(context, 12f), 0, 0)
    }




    if ("2" == AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.source_time_align) {
        val layoutNormalInfo: View = mRootView.findViewById(R.id.normalInfoLayout)
        val lp = layoutNormalInfo.layoutParams as LinearLayout.LayoutParams
        lp.gravity = Gravity.CENTER_HORIZONTAL
        layoutNormalInfo.requestLayout()
    }
    //是否显示阅读数 当阅读数接口没有请求成功之前才设置
    initNormalReadView()
    if (!readResponsed) {
        setNormalReadNumber(article.hitCount)
    }
    updateSpiderViewUI()

}

fun ImageTextDetailFragment2.updateSpiderViewUI() {
    if (article.spider != null) {
        mRootView.findViewById<ViewStub>(R.id.vsSpiderView)?.inflate()
        val spiderView: BaseSpiderView = mRootView.findViewById(R.id.spiderView)
        spiderView.call = this
        spiderView.setDate(article)
        tvSource.visibility = View.GONE
        tvAuthor.visibility = View.GONE
        val showTvAuthor = serverInfo.show_author == 1
        var contentAuthor = article.getAuthor()
        val boldAuthor = serverInfo.show_author_bold == 1
        val colorAuthor = serverInfo.show_author_color
        var isEPaper = false
        if(requireActivity() is ImageTextDetailActivity2){
            isEPaper = (requireActivity() as ImageTextDetailActivity2).isEpaper
        }
        if(isEPaper){
            tvAuthor.visibility=View.GONE
            ePagerAuthor.visibility=View.VISIBLE
            showView(true, contentAuthor, false, "#999999", ePagerAuthor,true, requireActivity())
        }else{
            showView(showTvAuthor, contentAuthor, boldAuthor, colorAuthor, tvAuthor,true, requireActivity())
        }
        //原来就默认不显示，不显示则就把该layout隐藏掉
        val showAuthorName = false
//        layoutAuthorName.visibility = if (showAuthorName) View.VISIBLE else View.GONE
//        layoutAuthorName.visibility = View.VISIBLE
        showView(
            showAuthorName,
            contentAuthor,
            boldAuthor,
            colorAuthor,
            tvAuthorBottom,
            false,
            requireActivity()
        )

        //是否显示发布日期
        val showTvPublishDate = serverInfo.content_show_publish_date == 1
        val contentPublishDate = article.publishdate_format
        val colorPublishDate = "#FF999999"
//        showView(
//            showTvPublishDate,
//            contentPublishDate,
//            false,
//            colorPublishDate,
//            tvPublishDate,
//            false,
//            requireActivity()
//        )
        if (showTvPublishDate) {
            tvPublishDate?.visibility = View.VISIBLE
            if (!TextUtils.isEmpty(colorPublishDate)) tvPublishDate?.setTextColor(Color.parseColor(colorPublishDate))
        } else {
            tvPublishDate?.visibility = View.GONE
        }

        //是否显示来源
        val showTvSource = serverInfo.content_show_source == 1
        var contentSource = article.referName
        if (contentSource.isNullOrEmpty()) {
            tvSource.visibility = View.GONE
            // contentSource = requireContext().resources.getString(R.string.app_name)
        } else {
            val boldSource = serverInfo.show_source_bold == 1
            val colorSource = serverInfo.show_source_color
            if(isEPaper){
                tvSource.visibility=View.GONE
                ePagerSource.visibility=View.VISIBLE
                //电子报来源颜色写死
                showView(
                    true,
                    contentSource,
                    false,
                    "#222222",
                    ePagerSource,
                    false,
                    requireActivity()
                )
            }else{
                showView(
                    showTvSource,
                    contentSource,
                    boldSource,
                    colorSource,
                    tvSource,
                    false,
                    requireActivity()
                )
            }


        }
    } else {
        var isEPaper = false
        if(requireActivity() is ImageTextDetailActivity2){
            isEPaper = (requireActivity() as ImageTextDetailActivity2).isEpaper
        }
        //是否显示来源
        val showTvSource = serverInfo.content_show_source == 1
        var contentSource = article.referName
        if (TextUtils.isEmpty(contentSource)) {
            tvSource.visibility = View.GONE
            // contentSource = requireContext().resources.getString(R.string.app_name)
        } else {
            val boldSource = serverInfo.show_source_bold == 1
            val colorSource = serverInfo.show_source_color
            if(isEPaper){
                //电子报来源颜色写死
                tvSource.visibility=View.GONE
                ePagerSource.visibility=View.VISIBLE
                //产品说报刊来源不受开关配置，默认显示
                showView(
                    true,
                    contentSource,
                    false,
                    "#222222",
                    ePagerSource,
                    false,
                    requireActivity()
                )
            }else{
            showView(
                showTvSource,
                contentSource,
                boldSource,
                colorSource,
                tvSource,
                false,
                requireActivity()
            )
            }
        }


        //是否显示作者
        val showTvAuthor = serverInfo.show_author == 1
        val contentAuthor = article.getAuthor()
        val boldAuthor = serverInfo.show_author_bold == 1
        val colorAuthor = serverInfo.show_author_color

        if(isEPaper){
            tvAuthor.visibility=View.GONE
            ePagerAuthor.visibility=View.VISIBLE
            showView(true, contentAuthor, false, "#999999", ePagerAuthor,true, requireActivity())
        }else{
            showView(showTvAuthor, contentAuthor, boldAuthor, colorAuthor, tvAuthor,true, requireActivity())
        }
        //是否显示发布日期
        val showTvPublishDate = serverInfo.content_show_publish_date == 1
        val contentPublishDate = article.publishdate_format
        val boldPublishDate = serverInfo.show_publish_date_bold == 1
        val colorPublishDate = serverInfo.show_publish_date_color
//        showView(
//            showTvPublishDate,
//            contentPublishDate,
//            boldPublishDate,
//            colorPublishDate,
//            tvPublishDate,
//            false,
//            requireActivity()
//        )

        if (!showTvSource && tvAuthor.visibility == View.VISIBLE) {
            val lp = tvPublishDate.layoutParams as ConstraintLayout.LayoutParams
            lp.topToBottom = R.id.authorName
            tvPublishDate.requestLayout()
        }

//        if (!showTvPublishDate) {
//            //不显示日期时，显示一排，跟iOS保持一致
//            val lp = tvReadNumber.layoutParams as ConstraintLayout.LayoutParams
//            if (tvAuthor.visibility == View.VISIBLE) {
//                lp.startToEnd = R.id.authorName
//                lp.topToTop = R.id.authorName
//            } else {
//                if (showTvSource) {
//                    lp.startToEnd = R.id.mNewsSource
//                    lp.topToTop = R.id.mNewsSource
//                }
//            }
//            tvReadNumber.requestLayout()
//        }


    }
}

/**
 *  初始化 阅读数控件
 */
fun ImageTextDetailFragment2.initNormalReadView() {
    if (article.showreadingcountflag == 1 && serverInfo.content_show_hit_count == 1) {
        tvReadNumber.visibility = View.VISIBLE
        var bold = serverInfo.show_hit_count_bold == 1
        var color = serverInfo.show_hit_count_color
        if (article.spider != null) {
            color = "#FF999999"
            bold = false
        }
        // tvReadNumber.text = "0"
        if (!TextUtils.isEmpty(color)) {
            tvReadNumber.setTextColor(Color.parseColor(color))
        }
        if (bold) tvReadNumber.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
    } else {
        tvReadNumber.visibility = View.GONE
    }
}

fun ImageTextDetailFragment2.setNormalReadNumber(number: Long) {
    val content = if (article.spider != null) {
        "全网传播量${StringUtils.toTenThousand(number)}"
    } else {
        //number.toString() + "浏览"
        "全网传播量${StringUtils.toTenThousand(number)}"
    }
    article.hitCount=number
    if (article.refreshHitCount()) {
        FacadeInvoker.postDelay(false)
    }
    tvReadNumber.text = content
}

/**
 * 免责声明 在网页加载完成后再去设置
 */
fun ImageTextDetailFragment2.setDisclaimer() {
    if (serverInfo.content_show_disclaimer == 1 && article.disclaimer != null && !fromMicroLive) {
        var name = article.disclaimer.name
        val value = article.disclaimer.value
        if (!TextUtils.isEmpty(value)) {
            if (TextUtils.isEmpty(name)) {
                name = getString(R.string.disclaimer)
            }
            val style = SpannableStringBuilder("$name:$value")
            style.setSpan(
                StyleSpan(Typeface.BOLD),
                0,
                name.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            val mDisclaimer = mRootView.findViewById<TextView>(R.id.mDisclaimer)
            mDisclaimer.visibility = View.VISIBLE
            mDisclaimer.text = value
        }
    }
}

/**
 * 责任编辑 在网页加载完成后再去设置
 */
fun ImageTextDetailFragment2.zerenbianji() {
    //是否显示责任编辑
    val showTvEditor =
        serverInfo.content_show_responsible_editor == 1 && !fromMicroLive && !TextUtils.isEmpty(
            article.zerenbianji
        )
    val contentEditor = getString(R.string.dutyEdit) + article.zerenbianji
    val boldEditor = serverInfo.show_responsible_editor_bold == 1
    val colorEditor = serverInfo.show_responsible_editor_color
    showView(
        showTvEditor,
        contentEditor,
        boldEditor,
        colorEditor,
        mRootView.findViewById(R.id.mDuty),
        false,
        requireActivity()
    )
}

fun ImageTextDetailFragment2.initWeatherView() {
    if (serverInfo.show_weather == 1) {
        mRootView.findViewById<ViewStub>(R.id.vsWeatherView).inflate()
        if (weatherSetter == null) {
            weatherSetter = WeatherSetter(mRootView.findViewById(R.id.weatherView))
        }
    }
}

private fun showView(
    show: Boolean,
    content: String?,
    bold: Boolean,
    color: String?,
    textView: TextView?,
    isAuthor: Boolean,
    activity: Activity?
) {
    if (show && !TextUtils.isEmpty(content)) {

        textView?.visibility = View.VISIBLE
//        if (isAuthor && (activity as ImageTextDetailActivity2).isEpaper) {
//            textView!!.text = "记者："
//        }
        //没看懂是什么操作，会显示两个时间
        if (!textView!!.text.contains(content!!)) {
            textView.append(content)
        }
        if (!TextUtils.isEmpty(color)) textView?.setTextColor(Color.parseColor(color))
        if (bold) {
            val typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
            textView?.typeface = typeface
        }
    } else {
        textView?.visibility = View.GONE
    }
}


fun ImageTextDetailActivity2.initPayView() {
    findViewById<ViewStub>(R.id.vsPayView).inflate()
    tvPayTips = findViewById(R.id.tv_pay_tips)
    paySeeMoreLayout = findViewById(R.id.pay_see_more_layout)
    playHowMuch = findViewById(R.id.pay_how_much)
    tvVipPayHowMuch = findViewById(R.id.tv_vip_pay_how_much)

    normalPayUtil = NormalPayUtil(this, catalogItem, object : Others {
        override fun getVipPayView(): TextView {
            return tvVipPayHowMuch
        }

        override fun operation(): String {
            return getString(R.string.pay_buy_article)
        }

        override fun payView(): MutableList<View>? {
            val payView: MutableList<View> = ArrayList()
            payView.add(paySeeMoreLayout)
            return payView
        }

        override fun paidView(): MutableList<View>? {
            return null
        }

        override fun openView(): TextView {
            return if (isMember) {
                tvVipPayHowMuch
            } else playHowMuch
        }
    }, object : PaidContentListener {
        override fun onPaidContent(meta: PaidMetas) {
            imageTextDetailFragment.updateBuyContent(meta)
            imageTextDetailFragment.showHTMLData(meta.content)
        }
    }, false, this)
}

fun ImageTextDetailFragment2.detailActivity(): ImageTextDetailActivity2? {
    val activity = requireActivity()
    return if (activity is ImageTextDetailActivity2) {
        activity
    } else {
        null
    }
}


/**
 * 查看原文点击及禁止转载显示与否
 * @receiver ImageTextDetailFragment2
 */
fun ImageTextDetailFragment2.setOriginAndReprint() {
    if (activity?.isFinishing == true || activity?.isDestroyed == true) {
        return
    }
    layoutAuthorName.visibility = View.GONE
    article.extension?.let {
        if (it.originalFlag == 0) {//非原创
            originalLabel.visibility = View.GONE
        } else {
            originalLabel.visibility = View.VISIBLE
        }
        if (!TextUtils.isEmpty(it.originalLinkUrl)) {
            layoutAuthorName.visibility = View.VISIBLE
            tvOriginal.visibility = View.VISIBLE
            tvOriginal.setOnClickListener {
                if (isFastClick()){
                    WebViewPageActivity.start(
                        "",
                        article.extension.originalLinkUrl,
                        activity
                    )
                }

            }
        } else {
            layoutAuthorName.visibility = View.GONE
            tvOriginal.visibility = View.GONE
        }
        if (it.reprintFlag == 0) {
            tvReprint.visibility = View.VISIBLE
        } else {
            tvReprint.visibility = View.GONE
        }
        if ((activity is ImageTextDetailActivity2) && (activity as ImageTextDetailActivity2).isEpaper) {
            tvReprint.visibility = View.GONE
        }

        bottomLine.visibility = View.VISIBLE
    }

}